package com.example.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import com.example.dao.ReleaseNoteDao;
import com.example.entity.ReleaseNote;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository("ReleaseNoteDao")
public class ReleaseNoteDaoImpl implements ReleaseNoteDao {

    @PersistenceContext // (unitName = "entityManagerFactory")
    EntityManager em;

    @Transactional
    public void saveReleaseNote(ReleaseNote releaseNote) {
        if (releaseNote.getObjId() == null)
            em.persist(releaseNote);
        else
            em.merge(releaseNote);
    }

    @Transactional
    public ReleaseNote getReleaseNote(Long objId) {
        ReleaseNote releaseNote = null;
        releaseNote = em.find(ReleaseNote.class, objId);
        return releaseNote;
    }

    @Transactional
    public List<ReleaseNote> getAllReleaseNotes() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<ReleaseNote> q = cb.createQuery(ReleaseNote.class);
        Root<ReleaseNote> root = q.from(ReleaseNote.class);
        q.distinct(true);
        q.select(root);
        q.orderBy(cb.asc(root.get("objId")));
        return em.createQuery(q).getResultList();
    }

    @Transactional
    public void deleteReleaseNote(Long objId) {
        ReleaseNote releaseNote = getReleaseNote(objId);
        if (releaseNote != null) {
            em.remove(releaseNote);
        } else {
            System.out.println("try to delete null;objiId:" + String.valueOf(objId));
        }
    }
}
